package com.example.programming.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.programming.common.Result;
import com.example.programming.common.tools.BaseController;
import com.example.programming.sys.entity.Chapter;
import com.example.programming.sys.entity.Course;
import com.example.programming.sys.entity.EduCourse;
import com.example.programming.sys.entity.Homework;
import com.example.programming.sys.mapper.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 课程 前端控制器 chrimer
 * </p>
 *
 * @author chrimer
 * @since 2020-06-25
 */
@RestController
@MapperScan("com.example.programming")
@RequestMapping("/sys/course")
public class CourseController extends BaseController {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private EduCourseMapper eduCourseMapper;

    @RequestMapping(method = RequestMethod.POST, value = "/page")
    public Result page(
            Integer pageNum,
            Integer pageSize) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);

        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/staffpage")
    public Result staffpage(
            Integer pageNum,
            Integer pageSize,
            String id,
            String course) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);

        if (id != null && !"".equals(id)) {
            //列名column要和数据库的一样
            warpper.like("id", id);
        }
        if (course != null && !"".equals(course)) {
            //列名column要和数据库的一样
            warpper.like("course", course);
        }
        warpper.eq("audit_status", 0);
        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/detailschool")
    public Result detailschool(
            Integer pageNum,
            Integer pageSize,
            String school) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);
        warpper.eq("school", school);
        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public Result save(@RequestBody Course entity) {
        Result result = new Result();
        if (entity.getId() == null) {
            courseMapper.insert(entity);
        } else {
            courseMapper.updateById(entity);
        }
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updatestatus")
    public Result updatestatus(@RequestBody Course entity) {
        Result result = new Result();
        System.out.println("id:" + entity.getId());
        if (entity.getId() == null) {
            courseMapper.insert(entity);
        } else {
            courseMapper.updateById(entity);
        }
        return result;
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/delete")
    public Result delete(String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
        courseMapper.deleteBatchIds(deleteIds);
        return result;
    }

    @RequestMapping(method = RequestMethod.GET, value = "getrecommend")
    public Result getrecommend() {
        Result result = new Result();
        List<Object> list = new ArrayList<>();
        Random random = new Random(50);
//        int count = courseMapper.selectList(null).size();
        int count = courseMapper.selectCount(null);
        for (int i = 0; i < 50; i++) {
            int j = random.nextInt(count);
            Object temp = courseMapper.selectById(j);
            if (temp != null) {
                list.add(temp);
            } else {
                i--;
            }

        }
        result.setData(list);
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "getcount")
    public Result getcount(String name) {
        Result result = new Result();
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);
        warpper.eq("type", name);
        int count = courseMapper.selectCount(warpper);
        result.setData(count);
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/pagecourse")
    public Result pagecourse(
            Integer pageNum,
            Integer pageSize,
            String name) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);
        warpper.eq("type", name);
        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    //用于顶层标题栏课程搜索
    @RequestMapping(method = RequestMethod.POST, value = "/searchpage")
    public Result searchpage(
            Integer pageNum,
            Integer pageSize,
            String course) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);
        warpper.like("course", course);
        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/searchcourse1")
    public Result searchcourse1(Integer id) {
        Result result = new Result();
        result.setData(courseMapper.selectById(id));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "searchcount")
    public Result searchcount(String name) {
        Result result = new Result();
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);
        warpper.eq("type", name);
        int count = courseMapper.selectCount(warpper);
        result.setData(count);
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/courseList")
    public Result courseList(
            Integer pageNum,
            Integer pageSize,
            String id,
            String course) {
        Result result = new Result();
        Page<Course> page = new Page<Course>(pageNum, pageSize);
        Course parms = new Course();
        QueryWrapper<Course> warpper = new QueryWrapper<Course>(parms);

        if (id != null && !"".equals(id)) {
            //列名column要和数据库的一样
            warpper.like("id", id);
        }
        if (course != null && !"".equals(course)) {
            //列名column要和数据库的一样
            warpper.like("course", course);
        }
        warpper.eq("audit_status", 1);
        result.setData(courseMapper.selectPage(page, warpper));
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/courseDelete")
    public Result courseDelete(String id) {
        Result result = new Result();
        Course course = new Course();
        course.setId(id);
        QueryWrapper wrapper = new QueryWrapper<Course>(course);
        courseMapper.delete(wrapper);
        result.success("删除成功");
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/getbycourse")
    public Result getbycourse(String name, String teacher) {
        Result result = new Result();
        Course course = new Course();
        course.setCourse(name);
        course.setTeacher(teacher);
        QueryWrapper wrapper = new QueryWrapper<Course>(course);
        result.setData(courseMapper.selectOne(wrapper));
        return result;
    }

    /**
     * 根据老师name获取该老师的全部课程
     *
     * @param name
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public Result getCourseByTeacherName(@PathVariable("id") String name) {
        Result result = new Result();
        QueryWrapper warpper = new QueryWrapper<Course>();
        warpper.eq("teacher", name);
        result.setData(courseMapper.selectList(warpper));
        return result;
    }

    /**
     * 获取当前课程的全部章节小节
     *
     * @param id
     * @return
     */
    @GetMapping("chapter/{id}")
    public Result getChapter(@PathVariable("id") String id) {
        Result result = new Result();
        QueryWrapper warpper = new QueryWrapper<Chapter>();
        Course course = courseMapper.selectById(id);
        warpper = new QueryWrapper<Chapter>().eq("course", course.getCourse()).orderByAsc("chapter_sort");
        List<Chapter> chapter = chapterMapper.selectList(warpper);
        for (Chapter chapter1 : chapter) {
            Homework homework = homeworkMapper.selectOne(new QueryWrapper<Homework>().eq("chapter_id", chapter1.getId()));
            chapter1.setHomework(homework == null ? null : homework.getHomeworkName());
        }

        result.setData(chapter);
        return result;
    }

    /***
     * 上传图片解析成base64
     * @param file
     * @return
     * @throws IOException
     */
//    @PostMapping("/upload")
//    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
//        Result result = new Result();
//        BASE64Encoder encoder = new BASE64Encoder();
//        String imgData = encoder.encode(file.getBytes());
//        result.success("data:image/jpeg;base64," + imgData);
//        return result;
//    }

    /**
     * 新增课程
     *
     * @param course
     * @return
     */
    @PostMapping("create")
    public Result create(@RequestBody Course course) {

        Result result = new Result();
        course.setId(UUID.randomUUID().toString().replace("-", ""));
        courseMapper.insert(course);
        result.success("");
        return result;
    }

    /**
     * 通过id获取全部信息
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    public Result info(@PathVariable("id") String id) {
        Result result = new Result();
        result.setData(courseMapper.selectById(id));
        return result;
    }

    /**
     * 作业完成情况
     *
     * @param id
     * @return
     */
    @GetMapping("completeInfo/{id}")
    public Result completeInfo(@PathVariable("id") Integer id) {
        Result result = new Result();
        List<Map<Integer, Integer>> list = studentMapper.completeInfo(id);
        List<String> xList = new LinkedList<>();
        List<Integer> yList = new LinkedList<>();
        for (Map<Integer, Integer> map : list) {
            xList.add("第" + map.get("x") + "章");
            yList.add(map.get("y"));
        }
        Map<String, Object> data = new HashMap<>();
        data.put("xList", xList);
        data.put("yList", yList);
        result.setData(data);
        return result;
    }

    /**
     * 学生成绩报表
     * @param id
     * @return
     */
    @GetMapping("getGradeTotal/{id}")
    public Result getGradeTotal(@PathVariable("id") Integer id) {
        Result result = new Result();
        List<Long> list = studentMapper.getGradeTotal(id);
        List<String> xList = new LinkedList<>();
        List<Long> yList = new LinkedList<>();


        xList.add("不及格");
        yList.add(list.stream().filter(i -> i < 60).count());

        xList.add("60~70");
        yList.add(list.stream().filter(map -> 60 <= map && map < 70).count());

        xList.add("70~80");
        yList.add(list.stream().filter(map -> 70 <= map && map < 80).count());

        xList.add("80~90");
        yList.add(list.stream().filter(map -> 80 <= map && map < 90).count());

        xList.add("90~100");
        yList.add(list.stream().filter(map -> 90 <= map && map <= 100).count());


        Map<String, Object> data = new HashMap<>();
        data.put("xList", xList);
        data.put("yList", yList);
        result.setData(data);
        return result;
    }


    @RequestMapping(method= RequestMethod.POST,value="/getCourses")
    public Result getCourses(String account) {
        Result result = new Result();
        List<EduCourse> list = eduCourseMapper.getCourse();
        List<EduCourse> myCourse = new ArrayList<>();
        while(myCourse.size()!=4){
            int temp = Math.abs(new Random().nextInt()%list.size());
            myCourse.add(list.get(temp));
        }

        result.setData(myCourse);
        result.success();
        return result;
    }
}

